<template>
  <div class="category-page">
    <!-- 新增标题栏 -->
    <div class="page-header">
      <div class="header-title">
        <div class="blue-line"></div>
        <span>课程分类</span>
        <div class="header-divider"></div>
      </div>
    </div>
    
    <!-- 顶部操作栏 -->
    <div class="toolbar">
      <el-input
        v-model="searchKey"
        placeholder="请输入分类名称关键字"
        class="search-input"
        clearable
        @keyup.enter="onSearch"
        @clear="onSearch"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="onSearch"></el-button>
        </template>
      </el-input>
      <div class="toolbar-actions">
        <el-button color="#2561EF" @click="onAddCategory">+ 新增分类</el-button>
        <el-button @click="onBatchDelete">批量删除</el-button>
      </div>
    </div>

    <!-- 树形表格 -->
    <el-table
      :header-cell-class-name="headerCellClassName"
      :row-class-name="tableRowClassName"
      :data="treeData"
      style="width: 100%"
      row-key="objectId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      default-expand-all
    >
      <el-table-column prop="name" label="分类名称" width="300" />
      <el-table-column prop="courseCount" label="课程数量" width="120" />
      <el-table-column label="描述" width="550" align="center">
        <template #default="scope">
          {{ scope.row.description || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button type="text" style="color: #2561EF" @click="onAddSubCategory(scope.row)">添加下级分类</el-button>
          <el-button type="text" style="color: #2561EF" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" style="color: #2561EF" @click="handleDelete(scope.row.objectId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 新增标签弹层 -->
    <div class="add-form">
      <el-dialog
        :title="dialogType === 'add' ? '添加分类' : '编辑分类'"
        v-model="dialogFormVisible"
        width="500px"
      >
        <el-form :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="课程数量" prop="courseCount">
            <el-input v-model="formData.courseCount" placeholder="请输入课程数量" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="formData.description" type="textarea" placeholder="请输入描述信息" />
          </el-form-item>
          <el-form-item label="分类等级" prop="level">
            <el-input v-model="formData.level" placeholder="请输入分类等级" />
          </el-form-item>
          <el-form-item label="等级序号" prop="order">
            <el-input v-model="formData.order" placeholder="请输入等级序号" />
          </el-form-item>
          <el-form-item label="父类" prop="parentId" v-if="dialogType === 'add'">
            <el-select v-model="formData.parentId" placeholder="请选择父类" clearable style="width: 100%">
              <el-option label="无父类（顶级分类）" value="" />
              <el-option
                v-for="item in allCategories"
                :key="item.objectId"
                :label="item.name"
                :value="item.objectId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useCategoryData } from '../hook/useCategoryData'
import { useCategoryForm } from '../hook/useCategoryForm'
import { useTableStyle } from '../hook/useTableStyle'
import { categoryAdd, categoryEdit, categoryList } from '../http/category'
import { Row } from 'element-plus/es/components/table-v2/src/components/index.mjs'

// 使用hook
const { treeData, searchKey, fetchCategoryList, deleteCategory } = useCategoryData()
const {
  dialogFormVisible,
  dialogType,
  formData,
  rules,
  currentEditId,
  cleanFormData,
  openAddForm,
  openEditForm,
  resetForm
} = useCategoryForm()
const { headerCellClassName, tableRowClassName } = useTableStyle()

// 所有分类数据（用于父类选择）
const allCategories = ref<any[]>([])

onMounted(() => {
  fetchCategoryList()
  fetchAllCategories()
})

// 获取所有分类（用于父类选择器）
async function fetchAllCategories() {
  try {
    const response = await categoryList()
    allCategories.value = response.data.results || []
  } catch (error) {
    console.error('获取所有分类失败:', error)
  }
}

//搜素
function onSearch() {
  fetchCategoryList()
}

//新增分类
function onAddCategory() {
  openAddForm()
}

function onAddSubCategory(row: any) {
  openAddForm(row)
}

function handleEdit(row: any) {
  openEditForm(row)
}

async function handleDelete(objectId: string) {
  try {
    await ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteCategory(objectId)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

function onBatchDelete() {
  // 批量删除逻辑
}

async function handleDialogConfirm() {
  const data = cleanFormData(formData.value)
  
  // 处理父类信息
  if (data.parentId) {
    const parentCategory = allCategories.value.find(item => item.objectId === data.parentId)
    if (parentCategory) {
      data.parent = parentCategory.name
    }
  } else {
    data.parent = ''
    data.parentId = ''
  }
  
  try {
    if (dialogType.value === 'add') {
      await categoryAdd(data)
      ElMessage.success('添加成功')
    } else if (dialogType.value === 'edit' && currentEditId.value) {
      await categoryEdit(currentEditId.value, data)
      ElMessage.success('编辑成功')
    }
    dialogFormVisible.value = false
    await fetchCategoryList()
    await fetchAllCategories() // 刷新父类选择器数据
  } catch (error) {
    ElMessage.error(error.response?.data?.error || '操作失败')
  }
}
</script>
<style scoped>
/* 新增标题栏样式 */
.page-header {
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.blue-line {
  width: 4px;
  height: 16px;
  background-color: #2561EF;
  margin-right: 8px;
  border-radius: 2px;
}

.header-title span {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.header-divider {
  height: 1px;
  background-color: #e8e8e8;
  margin-left: 20px;
  width: 90%;
}
.category-page {
  padding: 20px;
  background: #fff;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}

.search-input {
  width: 260px;
}

.toolbar-actions > .el-button {
  margin-left: 10px;
}

/* 鼠标悬停时整行蓝色描边 */
:deep(.el-table__body tr.custom-row:hover) {
  box-shadow: 0 0 0 2px #2561EF;
  border-radius: 6px;
  background: #fff;
  position: relative;
  z-index: 1;
}

/* 分类名称表头灰色背景 - 更精确的选择器 */
:deep(.el-table thead .el-table__cell.header-gray-bg) {
  background-color: #f5f7fa !important;
}

/* 圆角效果 */
:deep(.el-table__body tr.custom-row:hover > td:first-child) {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
}

:deep(.el-table__body tr.custom-row:hover > td:last-child) {
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
}

/* 分类名称表头灰色背景 */
:deep(.el-table .header-gray-bg) {
  background-color: #F9F9F9 !important;
}
</style>